#include "sqlite3_test.h"


int printCallBack(void* pv, int argc, char** argv, char** col)
{
    int i;
    for(i = 0; i < argc; i++)
    {
        printf("%s\t%s\n", col[i], argv[i]);
    }

    return 0;
}

int insertSqlite(sqlite3* db)
{
    int ret;
    char* errmsg;
    char sql[1024];
    char name[32];
    int id;
    int score;

    printf("insert name:\n");
    scanf("%s", name);
    getchar();

    printf("insert id:\n");
    scanf("%d", &id);
    getchar();

    printf("insert score:\n");
    scanf("%d", &score);
    getchar();

    sprintf(sql, "insert into stu values ('%s', %d, %d);", name, id, score);

    ret = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (SQLITE_OK != ret)
    {
        printf("%s\n", errmsg);
    } else {
        printf("insert sqlite success\n");
    }

    return 0;
}

int deleteSqlite(sqlite3 *db)
{
    int ret;
    char* errmsg;
    char sql[1024];
    char name[32];

    printf("insert name:\n");
    scanf("%s", name);
    getchar();

    sprintf(sql, "delete from stu where name='%s';", name);

    ret = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (SQLITE_OK != ret)
    {
        printf("%s\n", errmsg);
    } else {
        printf("delete sqlite success\n");
    }

    return 0;
}

int updateSqlite(sqlite3 *db)
{
    int ret;
    char* errmsg;
    char sql[1024];
    char name[32];
    int id;
    int score;

    printf("insert name:\n");
    scanf("%s", name);
    getchar();

    printf("insert id:\n");
    scanf("%d", &id);
    getchar();

    printf("insert score:\n");
    scanf("%d", &score);
    getchar();

    sprintf(sql, "update stu set id=%d, score=%d where name = '%s';", id, score, name);

    ret = sqlite3_exec(db, sql, NULL, NULL, &errmsg);
    if (SQLITE_OK != ret)
    {
        printf("%s\n", errmsg);
    } else {
        printf("update sqlite success\n");
    }

    return 0;
}

int querySqlite(sqlite3 *db)
{
    int ret;
    char* errmsg;
    char sql[1024] = "select * from stu;";

    ret = sqlite3_exec(db, sql, printCallBack, NULL, &errmsg);
    if (SQLITE_OK != ret)
    {
        printf("%s\n", errmsg);
    } else {
        printf("query sqlite success\n");
    }

    return 0;
}

int quitSqlite(sqlite3 *db)
{
    int ret = sqlite3_close(db);
    if (SQLITE_OK != ret)
    {
        printf("%s\n", sqlite3_errmsg(db));
    } else {
        printf("close sqlite success\n");
    }
    exit(0);
    
    return 0;
}

